const amountKey = {
    // cgsl: "",
    zczb: "",
    money: "",
    ajje: "",
    jyje: "",
    rzje: "",
    jzgb: "",
    pxze: "",
    gmgs: "",
};

export function toPercentage(num, fixed = 2) {
    if (Number.isNaN(Number(num))) {
        return num;
    }
    const [a, b] = (Number(num) * 100).toFixed(fixed).split(".");
    let c = "";
    for (let i = b.length - 1; i >= 0; i--) {
        if (b[i] !== "0") {
            c = b[i] + c;
        }
    }
    if (!c) {
        return `${a}%`;
    }
    return `${a}.${c}%`;
}

export function handleAmount(str, handleFunc) {
    if (!str) {
        if (handleFunc) {
            return handleFunc(str, false);
        }
        return str;
    }
    const num = Number(str);
    if (!num) {
        if (handleFunc) {
            return handleFunc(str, false);
        }
        return str;
    }
    str = (Math.round(num * 100) / 100).toFixed(2);
    const len = str.length;
    let perfix = "";
    let number = str.slice(0, len - 3);
    if (number?.[0] === "-") {
        number = number.slice(1);
        perfix = "-";
    }
    const suffix = str.slice(len - 3);
    const arr = [];
    const numberLen = number.length;
    let i = numberLen % 3;
    if (i !== 0) {
        arr.push(number.slice(0, i));
    }
    for (; i < numberLen; i += 3) {
        arr.push(number.slice(i, i + 3));
    }
    if (handleFunc) {
        return handleFunc(perfix + arr.join(",") + suffix, true);
    }
    return perfix + arr.join(",") + suffix;
}

export function wyAmountHandleFunc(data, ok) {
    if (!ok) {
        return "-";
    }
    return `${data}万元`;
}

export function defaultAmountHandleFunc(data, ok) {
    if (!ok) {
        return "-";
    }
    return data;
}

export function handleRes(obj, prefixObj = {}) {
    if (!obj) {
        return;
    }
    if (Array.isArray(obj)) {
        const res = [];
        for (let i = 0; i < obj.length; i++) {
            res[i] = handle(obj[i], prefixObj);
        }
        return res;
    }
    return handle(obj, prefixObj);
}

export function handleLines(str, prefix) {
    return `${prefix || ""}${str || "-"}`
        .split("\n")
        .map((i) => `<div class="full">${i}</div>`)
        .join("");
}

function handle(obj, prefixObj) {
    const res = {};
    for (const key in obj) {
        if (Object.hasOwnProperty.call(obj, key)) {
            let ele = obj[key];
            if (typeof ele === "string") {
                ele = ele.replace(/<[^>]+>/g, "");
            }
            if (key in amountKey) {
                ele = handleAmount(ele);
            }
            if (key in prefixObj) {
                res[key] = handleLines(ele, prefixObj[key]);
            } else {
                res[key] = ele ?? "-";
            }
        }
    }
    return res;
}
